package com.pn.warehouse.filter;

import com.alibaba.fastjson.JSON;
import com.pn.warehouse.entity.Result;
import com.pn.warehouse.exception.BusinessException;
import com.pn.warehouse.utils.WarehouseConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

//自定义过滤器限制登陆
public class LoginCheckFilter implements Filter {

    //注入redisTemplate
    private StringRedisTemplate redisTemplate;
    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //过滤器拦截到请求的方法
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        //1.白名单请求放行(不需要拦截的请求)
        //把不需要拦截的请求放到集合中
        List<String> urlList = new ArrayList<>();
        urlList.add("/captcha/captchaImage");
        urlList.add("/login");
        urlList.add("/logout");
        urlList.add("/product/img-upload");
        //拿到当前的请求
        String url = request.getServletPath();
        //判断是否需要放行
        if (urlList.contains(url) || url.contains("/img/upload")){
            filterChain.doFilter(request, response);//放行
            return;
        }

        //2.其他请求判断是否携带token，以及redis是否存在token
        //在请求头中拿到token
        String token = request.getHeader(WarehouseConstants.HEADER_TOKEN_NAME);
        //如果有，说明已经登陆过，放行
        if (StringUtils.hasText(token) && redisTemplate.hasKey(token)){
            filterChain.doFilter(request, response);//放行
            return;
        }
        //如果没有，请求不放行，并给前端做出响应
        Result err = Result.err(Result.CODE_ERR_UNLOGINED, "您尚未登陆！");
        String jsonErr = JSON.toJSONString(err);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(jsonErr);
        out.flush();
        out.close();
    }

}
